//
//  SweetheartView.m
//  Molian
//
//  Created by xiaocankeji on 15/8/27.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//

#import "SweetheartView.h"
#import "MLUserDataViewController.h"
#import "UIButton+WebCache.h"
#import "ChatViewController.h"
#import "UIImageView+WebCache.h"

#define kChiefViewHeight DeviceWidth/3*2
#define kSweetheartsViewHeight  58
#define kBtTextOfsetDown 10
@interface SweetheartView ()
@property BOOL poke;
@property BOOL kiss;
@end
@implementation SweetheartView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        if (IS_IPHONE_6) {
            self.textSize = 15;
        }else if(IS_IPHONE_6_PLUS){
            self.textSize = 16;
        }else{
            self.textSize = 14;
        }
        
        
        self.userEnabled = NO;
        self.sweetheartUser = nil;
        self.backgroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, self.frame.size.height - kChiefViewHeight - kSweetheartsViewHeight)];
        self.backgroundImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBackgroudImageView)];
        [self.backgroundImageView addGestureRecognizer:tapGR];
        UIImage *img = [UIImage imageNamed:@"背景"];
        UIImage *newImage = [SweetheartView imageWithImageSimple:img scaledToSize:CGSizeMake(self.backgroundImageView.frame.size.width, self.backgroundImageView.frame.size.height)];
        self.backgroundImageView.image = newImage;
        [self addSubview:self.backgroundImageView];
        
        UIButton *changeBackgroundImage = [UIButton buttonWithType:UIButtonTypeCustom];
        changeBackgroundImage.frame = CGRectMake(self.backgroundImageView.frame.size.width-45, self.backgroundImageView.frame.size.height-45, 45, 45);
        [changeBackgroundImage setImage:[UIImage imageNamed:@"换背景"] forState:UIControlStateNormal];
        [changeBackgroundImage setImageEdgeInsets:UIEdgeInsetsMake(12.5, 12.5, 12.5, 12.5)];
        [changeBackgroundImage addTarget:self action:@selector(changeBackgroundImage:) forControlEvents:UIControlEventTouchUpInside];
        [self.backgroundImageView addSubview:changeBackgroundImage];
        
        UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, self.backgroundImageView.frame.size.height, DeviceWidth, kChiefViewHeight+kSweetheartsViewHeight)];
        bottomView.backgroundColor = [UIColor clearColor];
        [self addSubview:bottomView];
        
        UIView *myAndTaHeadView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, kSweetheartsViewHeight)];
        myAndTaHeadView.backgroundColor = [UIColor whiteColor];
        [bottomView addSubview:myAndTaHeadView];
        
        
        //我的头像
        self.myHeadBt = [UIButton buttonWithType:UIButtonTypeCustom];
        self.myHeadBt.layer.masksToBounds = YES;
        self.myHeadBt.layer.cornerRadius = 20;
        self.myHeadBt.frame = CGRectMake(10, 10, 40, 40);
        
        
        [self.myHeadBt setImage:[UIImage imageNamed:@"空头像我"] forState:UIControlStateHighlighted];
         [self.myHeadBt setImage:[UIImage imageNamed:@"空头像我"] forState:UIControlStateNormal];
        [self.myHeadBt addTarget:self action:@selector(clickMyHeadBt) forControlEvents:UIControlEventTouchUpInside];
        [myAndTaHeadView addSubview:self.myHeadBt];
        [self login];
        //对方的头像
        self.taHeadBt = [UIButton buttonWithType:UIButtonTypeCustom];
        self.taHeadBt.layer.masksToBounds = YES;
        self.taHeadBt.layer.cornerRadius = 20;
        self.taHeadBt.frame = CGRectMake(55, 10, 40, 40);
        [self.taHeadBt setImage:[UIImage imageNamed:@"空头像ta"] forState:UIControlStateNormal];
        [self.taHeadBt setImage:[UIImage imageNamed:@"空头像ta"] forState:UIControlStateHighlighted];
        [self.taHeadBt addTarget:self action:@selector(clickTaHeadBt) forControlEvents:UIControlEventTouchUpInside];
        [myAndTaHeadView addSubview:self.taHeadBt];
        
        self.togetherLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 20, DeviceWidth - 120, 20)];
        self.togetherLabel.text = [NSString stringWithFormat:@"已经有%ld人找到了虚拟恋人",(long)[Utils getPocketloveNumber]];
        self.togetherLabel.adjustsFontSizeToFitWidth = YES;
        self.togetherLabel.textColor = RGBA(88, 88, 88, 1);
        self.togetherLabel.font = kFont(16);
        [myAndTaHeadView addSubview:self.togetherLabel];
        
        UIColor *lineColor = RGBA(233, 233, 233, 1);
        UIColor *textColor = RGBA(233, 233, 233, 1);
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, myAndTaHeadView.frame.size.height-0.5, DeviceWidth, 0.5)];
        line.backgroundColor = lineColor;
        [myAndTaHeadView addSubview:line];
        
        self.chiefViewTop = NO;
        self.chiefView = [[UIView alloc] initWithFrame:CGRectMake(0, kSweetheartsViewHeight, DeviceWidth, kChiefViewHeight)];
        self.chiefView.backgroundColor = [UIColor whiteColor];
        [bottomView addSubview:self.chiefView];
        
        
        
        //消息
        self.messageBt = [UIButton buttonWithType:UIButtonTypeCustom];
        self.messageBt.frame = CGRectMake(0 , 0, (DeviceWidth-1)/3, (DeviceWidth-1)/3);
        [self.messageBt setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
        [self.messageBt setBackgroundImage:[UIImage imageWithColor:textColor] forState:UIControlStateHighlighted];
        [self.messageBt setTitleColor: RGBA(38, 38, 38, 1) forState:UIControlStateNormal];
        [self.messageBt setTitle:@"消息" forState:UIControlStateNormal];
        [self.messageBt setTitleEdgeInsets:UIEdgeInsetsMake((DeviceWidth-1)/3*2/7+kBtTextOfsetDown, 0, 0, 0)];
        self.messageBt.titleLabel.font = kFont(self.textSize);
        self.messageImageView = [[UIImageView alloc] initWithFrame:CGRectMake((DeviceWidth-1)/3/2-14, (DeviceWidth-1)/3*2/7, 28, 28)];
        
        self.messageImageView.image = [UIImage imageNamed:@"空消息"];
        self.unreadMessagesLabel  = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 28-10, 12)];
        self.unreadMessagesLabel.textColor = [UIColor whiteColor];
        self.unreadMessagesLabel.textAlignment = NSTextAlignmentCenter;
        self.unreadMessagesLabel.font = kFont(12);
        self.unreadMessagesLabel.text = @"";
        self.unreadMessagesLabel.adjustsFontSizeToFitWidth = YES;
        [self.messageImageView addSubview:self.unreadMessagesLabel];
        
        [self.messageBt addSubview:self.messageImageView];
        
        
        [self.messageBt addTarget:self action:@selector(clickMessage:) forControlEvents:UIControlEventTouchUpInside];
        [self.chiefView addSubview:self.messageBt];
        
        //打电话
        self.telephoneBt = [UIButton buttonWithType:UIButtonTypeCustom];
        self.telephoneBt.frame = CGRectMake((DeviceWidth-1)/3+0.5 , 0, (DeviceWidth-1)/3, (DeviceWidth-1)/3);
        [self.telephoneBt setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
        [self.telephoneBt setBackgroundImage:[UIImage imageWithColor:textColor] forState:UIControlStateHighlighted];
        [self.telephoneBt setTitleColor: RGBA(38, 38, 38, 1) forState:UIControlStateNormal];
        [self.telephoneBt setTitle:@"打电话" forState:UIControlStateNormal];
        [self.telephoneBt setTitleEdgeInsets:UIEdgeInsetsMake((DeviceWidth-1)/3*2/7+kBtTextOfsetDown, 0, 0, 0)];
        self.telephoneBt.titleLabel.font = kFont(self.textSize);
        UIImageView *telephoneImageView = [[UIImageView alloc] initWithFrame:CGRectMake((DeviceWidth-1)/3/2-14, (DeviceWidth-1)/3*2/7, 28, 28)];
        telephoneImageView.image = [UIImage imageNamed:@"电话"];
        [self.telephoneBt addSubview:telephoneImageView];
        [self.telephoneBt addTarget:self action:@selector(clickTelephone:) forControlEvents:UIControlEventTouchUpInside];
        [self.chiefView addSubview:self.telephoneBt];
        
        //时间
        self.timeBt = [UIButton buttonWithType:UIButtonTypeCustom];
        self.timeBt.frame = CGRectMake((DeviceWidth-1)/3*2+1, 0, (DeviceWidth-1)/3, (DeviceWidth-1)/3);
        [self.timeBt setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
        [self.timeBt setBackgroundImage:[UIImage imageWithColor:textColor] forState:UIControlStateHighlighted];
        [self.timeBt setTitleColor: RGBA(38, 38, 38, 1) forState:UIControlStateNormal];
        [self.timeBt setTitle:@"时间" forState:UIControlStateNormal];
        [self.timeBt setTitleEdgeInsets:UIEdgeInsetsMake((DeviceWidth-1)/3*2/7+kBtTextOfsetDown, 0, 0, 0)];
        self.timeBt.titleLabel.font = kFont(self.textSize);
        UIImageView *timeImageView = [[UIImageView alloc] initWithFrame:CGRectMake((DeviceWidth-1)/3/2-14, (DeviceWidth-1)/3*2/7, 28, 28)];
        timeImageView.image = [UIImage imageNamed:@"时间"];
        [self.timeBt addSubview:timeImageView];
        [self.timeBt addTarget:self action:@selector(clickTime:) forControlEvents:UIControlEventTouchUpInside];
        [self.chiefView addSubview:self.timeBt];
        
        //戳一下
        self.pokeBt = [UIButton buttonWithType:UIButtonTypeCustom];
        self.pokeBt.frame = CGRectMake(0, (DeviceWidth-1)/3+0.5, (DeviceWidth-1)/3, (DeviceWidth-1)/3);
        [self.pokeBt setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
        [self.pokeBt setBackgroundImage:[UIImage imageWithColor:textColor] forState:UIControlStateHighlighted];
        
        [self.pokeBt setTitleColor: RGBA(38, 38, 38, 1) forState:UIControlStateNormal];
        [self.pokeBt setTitle:@"戳一下" forState:UIControlStateNormal];
        [self.pokeBt setTitleEdgeInsets:UIEdgeInsetsMake((DeviceWidth-1)/3*2/7+kBtTextOfsetDown, 0, 0, 0)];
        self.pokeBt.titleLabel.font = kFont(self.textSize);
        UIImageView *pokeImageView = [[UIImageView alloc] initWithFrame:CGRectMake((DeviceWidth-1)/3/2-14, (DeviceWidth-1)/3*2/7, 28, 28)];
        pokeImageView.image = [UIImage imageNamed:@"戳一下"];
        [self.pokeBt addSubview:pokeImageView];
        [self.pokeBt addTarget:self action:@selector(clickPoke:) forControlEvents:UIControlEventTouchUpInside];
        [self.chiefView addSubview:self.pokeBt];
        
        //么么哒
        self.kissBt = [UIButton buttonWithType:UIButtonTypeCustom];
        self.kissBt.frame = CGRectMake((DeviceWidth-1)/3+0.5, (DeviceWidth-1)/3+0.5, (DeviceWidth-1)/3, (DeviceWidth-1)/3);
        [self.kissBt setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
        [self.kissBt setBackgroundImage:[UIImage imageWithColor:textColor] forState:UIControlStateHighlighted];
        [self.kissBt setTitleColor: RGBA(38, 38, 38, 1) forState:UIControlStateNormal];
        [self.kissBt setTitle:@"么么哒" forState:UIControlStateNormal];
        [self.kissBt setTitleEdgeInsets:UIEdgeInsetsMake((DeviceWidth-1)/3*2/7+kBtTextOfsetDown, 0, 0, 0)];
        self.kissBt.titleLabel.font = kFont(self.textSize);
        UIImageView *kissImageView = [[UIImageView alloc] initWithFrame:CGRectMake((DeviceWidth-1)/3/2-14, (DeviceWidth-1)/3*2/7, 28, 28)];
        kissImageView.image = [UIImage imageNamed:@"么么哒"];
        [self.kissBt addSubview:kissImageView];
        [self.kissBt addTarget:self action:@selector(clickKiss:) forControlEvents:UIControlEventTouchUpInside];
        [self.chiefView addSubview:self.kissBt];
        
        
        UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(0, (DeviceWidth-1)/3, DeviceWidth, 0.5)];
        line1.backgroundColor = lineColor;
        [self.chiefView addSubview:line1];
        UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake((DeviceWidth-1)/3, 0, 0.5, kChiefViewHeight)];
        line2.backgroundColor = lineColor;
        [self.chiefView addSubview:line2];
        UIView *line3 = [[UIView alloc] initWithFrame:CGRectMake((DeviceWidth-1)/3*2+0.5, 0, 0.5, kChiefViewHeight)];
        line3.backgroundColor = lineColor;
        [self.chiefView addSubview:line3];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveMessage:) name:@"receiveMessage" object:nil];
        self.timeView = [self foundTimeView];
    }
    return self;
}
- (void)hint
{
    [HUD Prompt:@"还不能使用恋人互动功能，\n快去口袋里找个人一起用吧"];
}
- (void)clickBGView
{
    if (self.timeView.alpha == 0) {
        [Utils Hidden:self.timeView Bool:YES];
    }else{
        [Utils Hidden:self.timeView Bool:NO];
    }
    
}
- (UIView *)foundTimeView
{
    
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight)];
    bgView.backgroundColor = RGBA(1, 1, 1, 0.3);
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickBGView)];
    [bgView addGestureRecognizer:tap];
    bgView.alpha = 0;
    [[[UIApplication sharedApplication].delegate window] addSubview:bgView];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, 215)];
    view.backgroundColor = APPCOLOR(1);
    [bgView addSubview:view];
    self.surplusLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 40, DeviceWidth-100, 30)];
    self.surplusLabel.textColor = [UIColor whiteColor];
    self.surplusLabel.textAlignment = NSTextAlignmentCenter;
    self.surplusLabel.text = @"";
    self.surplusLabel.font = kFont(16);
    [view addSubview:self.surplusLabel];
    
    self.countDownLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, view.frame.size.height/2-30, DeviceWidth-40, 60)];
    self.countDownLabel.textColor = [UIColor whiteColor];
    self.countDownLabel.textAlignment = NSTextAlignmentCenter;
    self.countDownLabel.text = @"";
    self.countDownLabel.font = kFont(40);
    [view addSubview:self.countDownLabel];
    
    //    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, view.frame.size.height-50.5, DeviceWidth, 0.5)];
    //    lineView.backgroundColor = RGBA(200, 200, 200, 1);
    //    [view addSubview:lineView];
    
    self.relieveBt = [UIButton buttonWithType:UIButtonTypeCustom];
    self.relieveBt.frame = CGRectMake(0,view.frame.size.height-50,DeviceWidth,50);
    self.relieveBt.backgroundColor = [UIColor whiteColor];
    [self.relieveBt setTitle:@"" forState:UIControlStateNormal];
    self.relieveBt.titleLabel.font = kFont(16);
    [self.relieveBt setTitleColor: RGBA(155, 155, 155, 1) forState:UIControlStateHighlighted];
    [self.relieveBt addTarget:self action:@selector(clickRelieve:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:self.relieveBt];
    
    
    return bgView;
    
}
- (UIView *)redHotView
{
    if (_redHotView == nil) {
        _redHotView = [[UIView alloc] initWithFrame:CGRectMake(self.nameBt.frame.size.width/2 - 3, self.nameBt.frame.size.height - 15, 6, 6)];
        _redHotView.layer.masksToBounds = YES;
        _redHotView.layer.cornerRadius = 3;
        _redHotView.backgroundColor = APPCOLOR(1);
        _redHotView.hidden = YES;
        [self.nameBt addSubview:_redHotView];
    }
    _redHotView.frame = CGRectMake(self.nameBt.frame.size.width/2 - 3, self.nameBt.frame.size.height - 15, 6, 6);
    return _redHotView;
}
- (void)clickRelieve:(UIButton *)bt
{
    [Utils Hidden:self.timeView Bool:NO];
    if (self.userEnabled) {
        if ([bt.titleLabel.text isEqualToString:@"我要分手"]) {
            
            __block HUD*hud = [[HUD alloc]init];
            [hud HUDTitle:@"我要分手" TextStr:@"请输入理由" CANCEL:@"取消" Confirm:@"确定"];
            hud.Confirm  = ^{
                UITextField *tf = hud.textField;
                [AVAnalytics event:@"我要分手"]; // 通知服务器一个点击事件。
                [self separateAndseparateStr:tf.text];
            };
            hud.Cancel = ^{
                NSLog(@"取消");
            };
            [self addSubview:hud];
            
        }else if ([bt.titleLabel.text isEqualToString:@"继续领走"]) {
            
            
            if ([self.delegate respondsToSelector:@selector(pushChatViewControllerUser:isPay:)]) {
                
                bt.enabled = NO;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    bt.enabled = YES;
                });
                
                [self.delegate pushChatViewControllerUser:self.sweetheartUser isPay:YES];
            }
            
        }else{
            
        }
    }
    
}
- (void)separateAndseparateStr:(NSString *)str
{
    [AVCloud callFunctionInBackground:@"getNetTime" withParameters:nil block:^(id objectt, NSError *errorr) {
        
        if (!errorr) {
            NSString *time = objectt;
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:[time longLongValue]/1000];
            self.sweetheart.brokeUpDate = date;
            NSInteger count = [self manageDateBeginDate:self.sweetheart.togetherDate presentDate:[time longLongValue]/1000];
            self.sweetheart.togetherBefore += count/60;
            self.sweetheart.status = 0;
            [self.sweetheart saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    //分手成功
                    [self separateIsCommon:YES separateStr:str];
                    
                }else{
                    [HUD Prompt:@"分手失败"];
                }
            }];
        }else{
            [HUD Prompt:@"分手失败"];
        }
        
    }];
    //
}

- (void)changeBackgroundImage:(UIButton *)bt
{
    if (self.userEnabled) {
        FSMediaPicker *mediaPicker = [[FSMediaPicker alloc] init];
        mediaPicker.mediaType = FSMediaTypePhoto;
        mediaPicker.editMode = FSEditModeStandard;
        mediaPicker.delegate = self;
        [mediaPicker showFromView:self];
    }else{
        [self hint];
    }
}
- (void)mediaPicker:(FSMediaPicker *)mediaPicker didFinishWithMediaInfo:(NSDictionary *)mediaInfo
{
    UIImage* image;
    if(mediaPicker.editMode == FSEditModeStandard){
        image = mediaInfo.editedImage;
    }else {
        image = mediaInfo.originalImage;
    }
    float kCompressionQuality = 0.3;
    NSData *imgData = UIImageJPEGRepresentation(image, kCompressionQuality);
    // 后台上传照片
    AVFile *addPhoto = [AVFile fileWithName:@"photo.jpg" data:imgData];
    // 异步上传照片,上传成功之后再显示添加的照片
    [HUD setOnViewWithTitle:@"加载中" animated:YES];
    [addPhoto saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        [HUD hideFromViewAnimated:YES];
        if (succeeded) {
            self.sweetheart.background = addPhoto;
            [self.sweetheart saveInBackground];
            self.backgroundImageView.image = [SweetheartView imageWithImageSimple:image scaledToSize:CGSizeMake(self.backgroundImageView.frame.size.width, self.backgroundImageView.frame.size.height)];
            //发送透传告诉对方背景图片改变
            [self sendCmdChangeBackgroundUrl:addPhoto.url];
            
            [HUD hideFromViewAnimated:YES];
        } else {
            [HUD Prompt:@"上传图片失败,请重试"];
            [HUD hideFromViewAnimated:YES];
            return;
        }
        
    }];
    [HUD setOnViewWithTitle:nil animated:YES];
    
}
- (void)changeBackgroundUrl:(NSString *)url
{
    
    
    
    
    [self.backgroundImageView sd_setImageWithURL:[NSURL URLWithString:url] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
         self.backgroundImageView.image = [SweetheartView imageWithImageSimple:image scaledToSize:CGSizeMake(self.backgroundImageView.frame.size.width, self.backgroundImageView.frame.size.height)];
    }];
}
//发送透传告诉对方,我修改了背景图片
- (void)sendCmdChangeBackgroundUrl:(NSString *)url
{
    EMChatCommand *cmdChat = [[EMChatCommand alloc] init];
    cmdChat.cmd = ACTION_Pocketsweet_SwEET_IMG;
    EMCommandMessageBody *body = [[EMCommandMessageBody alloc] initWithChatObject:cmdChat];
    EMMessage *message = [[EMMessage alloc] initWithReceiver: self.sweetheartUser.objectId bodies:@[body]];
    message.messageType = eMessageTypeChat;
    message.ext = [NSDictionary dictionaryWithObjectsAndKeys:url,@"url", nil];
    
    [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:nil];
}
- (void)tapBackgroudImageView
{
    if (self.userEnabled) {
        
        if (self.chiefViewTop) {
            self.chiefViewTop = NO;
            [Utils animationMobileTimer:0.3 View:self.chiefView Rect:CGRectMake(0, kSweetheartsViewHeight, DeviceWidth, kChiefViewHeight)];
            [self.delegate changeTableViewHeightBOOL:NO];
        }else{
            self.chiefViewTop = YES;
            [Utils animationMobileTimer:0.3 View:self.chiefView Rect:CGRectMake(0, 0, DeviceWidth, kChiefViewHeight)];
            [self.delegate changeTableViewHeightBOOL:YES];
        }
    }
}
- (void)changeChiefViewFrame
{
    [Utils animationMobileTimer:0.2 View:self.chiefView Rect:CGRectMake(0, 0, DeviceWidth, kChiefViewHeight)];
    self.chiefViewTop = YES;
}
-(void)receiveMessage:(NSNotification *)notification
{
    if (self.userEnabled&&self.sweetheart&&self.sweetheartUser){
        NSDictionary *dic=[notification userInfo];
        EMMessage *message = [dic objectForKey:@"message"];
        if (message&&[message.from isEqualToString:self.sweetheartUser.objectId]&&[message.to isEqualToString:[MLUser currentUser].objectId]) {
            [self messageNumberChange];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"loveMessage" object:nil];
        }
    }
}
//分手
- (void)separateIsCommon:(BOOL)common separateStr:(NSString *)str
{
    if(str == nil ){
        str = @"";
    }
    
    if(common){
        NSString *sweetheartUserObjectId = self.sweetheartUser.objectId;
        NSString *sweetheartUserNickname = self.sweetheartUser.nickname;
        NSDictionary *params = @{@"touserId": sweetheartUserObjectId, @"fromuserId": [MLUser currentUser].objectId,@"nick":[MLUser currentUser].nickname,@"actions":ACTION_Pocketsweet_SWEET_DELETE,@"sweetId":self.sweetheart.objectId};
        [AVCloud callFunctionInBackground:@"sendSweetApplyCMDMsg" withParameters:params block
                                         :^(id object, NSError *error) {
            if (!error) {
                NSDictionary *paramsF = @{@"touserId": sweetheartUserObjectId,@"msg":[NSString stringWithFormat:@"%@和你分手了%@",[MLUser currentUser].nickname,str.length != 0?  [NSString stringWithFormat:@",原因:%@",str]:@""]};
                [AVCloud callFunctionInBackground:@"sendSysMsg" withParameters:paramsF block:^(id object, NSError *error) {
                    if (error) {
                       // NSLog(@"分手错误");
                    }
                }];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"sweetheartChange" object:self userInfo:nil];                
                [HUD Prompt:[NSString stringWithFormat:@"已和%@分手成功",sweetheartUserNickname]];
                self.chiefViewTop = YES;
                [Utils animationMobileTimer:0.3 View:self.chiefView Rect:CGRectMake(0, 0, DeviceWidth, kChiefViewHeight)];
                
            } else {
                [HUD Prompt:@"网络错误，返回重试"];
            }
        }];
    }else{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"sweetheartChange" object:self userInfo:nil];  
    }
    self.sweetheart = nil;
    self.userEnabled = NO;
    [self.taHeadBt setImage:[UIImage imageNamed:@"空头像ta"] forState:UIControlStateNormal];
    if (self.nameBt) {
        [self.nameBt setTitle:[NSString stringWithFormat:@""] forState:UIControlStateNormal];
    }
    UIImage *img = [UIImage imageNamed:@"背景"];
    UIImage *newImage = [SweetheartView imageWithImageSimple:img scaledToSize:CGSizeMake(self.backgroundImageView.frame.size.width, self.backgroundImageView.frame.size.height)];
    self.backgroundImageView.image = newImage;
    self.togetherLabel.text =[NSString stringWithFormat:@"已经有%ld人找到了虚拟恋人",(long)[Utils getPocketloveNumber]];
    if(_timeBtTimer){
        [_timeBtTimer invalidate];
        _timeBtTimer = nil;
    }
    self.sweetheartUser = nil;
    
}
//用户资料改变了
- (void)changeSweetheartData
{
    [self.nameBt setTitle:self.sweetheartUser.nickname forState:UIControlStateNormal];
    
    if (!self.sweetheartUser.subAvatar || [self.sweetheartUser.subAvatar isEqualToString:@""]) {
        [self.taHeadBt sd_setImageWithURL:[NSURL URLWithString:self.sweetheartUser.avatar.url] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"空头像ta"]];
        
    }else{
        [self.taHeadBt sd_setImageWithURL:[NSURL URLWithString:self.sweetheartUser.subAvatar] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"空头像ta"]];
    }
    
}
- (void)login
{
    MLUser *user = [MLUser currentUser];
    if (!user) {
        [self.myHeadBt setImage:[UIImage imageNamed:@"空头像我"] forState:UIControlStateNormal];
        return;
    }
    if (!user.subAvatar || [user.subAvatar isEqualToString:@""]) {
        [self.myHeadBt sd_setImageWithURL:[NSURL URLWithString:user.avatar.url] forState:UIControlStateNormal];
        
    }else{
        [self.myHeadBt sd_setImageWithURL:[NSURL URLWithString:user.subAvatar] forState:UIControlStateNormal];
    }
}
- (void)logOut
{
   // [self.myHeadBt setImage:[UIImage imageNamed:@"空头像我"] forState:UIControlStateNormal];
    UIImage *img = [UIImage imageNamed:@"背景"];
    UIImage *newImage = [SweetheartView imageWithImageSimple:img scaledToSize:CGSizeMake(self.backgroundImageView.frame.size.width, self.backgroundImageView.frame.size.height)];
    self.backgroundImageView.image = newImage;
    [self.messageBt setTitle:@"消息" forState:UIControlStateNormal];
    self.unreadMessagesLabel.text = @"";
    self.redHotView.hidden = YES;
    self.messageImageView.image = [UIImage imageNamed:@"空消息"];
    self.sweetheart = nil;
    if (self.nameBt) {
        [self.nameBt setTitle:[NSString stringWithFormat:@""] forState:UIControlStateNormal];
    }
    self.userEnabled = NO;
    [self.taHeadBt setImage:[UIImage imageNamed:@"空头像ta"] forState:UIControlStateNormal];
    self.togetherLabel.text = [NSString stringWithFormat:@"已经有%ld人找到了虚拟恋人",(long)[Utils getPocketloveNumber]];
    if(_timeBtTimer){
        [_timeBtTimer invalidate];
        _timeBtTimer = nil;
    }
    self.sweetheartUser = nil;
    self.chiefViewTop = NO;
    [Utils animationMobileTimer:0.3 View:self.chiefView Rect:CGRectMake(0, kSweetheartsViewHeight, DeviceWidth, kChiefViewHeight)];
}
//截取部分图像
+(UIImage*)myImage:(UIImage *)image rect:(CGRect)rect
{
    CGImageRef subImageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
    CGRect smallBounds = CGRectMake(0, 0, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));
    
    UIGraphicsBeginImageContext(smallBounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawImage(context, smallBounds, subImageRef);
    UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];
    UIGraphicsEndImageContext();
    
    return smallImage;
}
//压缩图片
+ (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    CGFloat w = newSize.width;
    CGFloat h = newSize.height;
    CGFloat width = image.size.width;
    CGFloat height = image.size.height;
    
    if (w/h == width/height) {
        return image;
    }else if(w/h>width/height){
        //需要比较宽的屏幕
        CGFloat radioH = width/w*h;
        return [SweetheartView myImage:image rect:CGRectMake(0, height/2-radioH/2, width, radioH)];
        
    }else{
        CGFloat radioW = height/h*w;
        return [SweetheartView myImage:image rect:CGRectMake(width/2-radioW/2, 0, radioW, height)];
    }
}

- (void)assignment
{
    self.kiss = NO;
    self.poke = NO;
    if ([self.sweetheart.sponsor.objectId isEqualToString:[MLUser currentUser].objectId]) {
        self.sweetheartUser = (MLUser*)self.sweetheart.winner;
    }else{
        self.sweetheartUser  = (MLUser*)self.sweetheart.sponsor;
    }
    MLUser *user = [MLUser currentUser];
    UIImage *img = [UIImage imageNamed:@"背景"];
    UIImage *newImage = [SweetheartView imageWithImageSimple:img scaledToSize:CGSizeMake(self.backgroundImageView.frame.size.width, self.backgroundImageView.frame.size.height)];
    self.backgroundImageView.image = newImage;
    [self.messageBt setTitle:@"消息" forState:UIControlStateNormal];
    self.unreadMessagesLabel.text = @"";
    self.redHotView.hidden = YES;
    self.messageImageView.image = [UIImage imageNamed:@"空消息"];
    [self.backgroundImageView sd_setImageWithURL:[NSURL URLWithString:self.sweetheart.background.url] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if (image) {
            UIImage *newImage = [SweetheartView imageWithImageSimple:image scaledToSize:CGSizeMake(self.backgroundImageView.frame.size.width, self.backgroundImageView.frame.size.height)];
            self.backgroundImageView.image = newImage;
        }else{
            
            UIImage *img = [UIImage imageNamed:@"背景"];
             UIImage *newImage = [SweetheartView imageWithImageSimple:img scaledToSize:CGSizeMake(self.backgroundImageView.frame.size.width, self.backgroundImageView.frame.size.height)];
            self.backgroundImageView.image = newImage;
        }
    }];
    
    if (!user.subAvatar || [user.subAvatar isEqualToString:@""]) {
        [self.myHeadBt sd_setImageWithURL:[NSURL URLWithString:user.avatar.url] forState:UIControlStateNormal];
        
    }else{
        [self.myHeadBt sd_setImageWithURL:[NSURL URLWithString:user.subAvatar] forState:UIControlStateNormal];
    }
    [self.taHeadBt setImage:[UIImage imageNamed:@"空头像ta"] forState:UIControlStateNormal];
    if (!self.sweetheartUser.subAvatar || [self.sweetheartUser.subAvatar isEqualToString:@""]) {
        [self.taHeadBt sd_setImageWithURL:[NSURL URLWithString:self.sweetheartUser.avatar.url] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"空头像ta"]];
        
    }else{
        [self.taHeadBt sd_setImageWithURL:[NSURL URLWithString:self.sweetheartUser.subAvatar] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"空头像ta"]];
    }
    if(_timeBtTimer){
        [_timeBtTimer invalidate];
        _timeBtTimer = nil;
    }
    
    
        self.surplusLabel.text = @"在一起";
        [self.relieveBt setTitle:@"我要分手" forState:UIControlStateNormal];
        [self.relieveBt setTitleColor: RGBA(55, 55, 55, 1) forState:UIControlStateNormal];
    
    
    
    [AVCloud callFunctionInBackground:@"getNetTime" withParameters:nil block:^(id objectt, NSError *errorr) {
        if (errorr) {
            [HUD Prompt:@"在一起时间加载错误"];
        }else{
            NSString *str = objectt;
            NSInteger count = [self manageDateBeginDate:self.sweetheart.togetherDate presentDate:[str longLongValue]/1000 ];
            count =count/60+ self.sweetheart.togetherBefore;
            
            if (count>60*24) {
                NSInteger a = count/1440;
                self.togetherLabel.text = [NSString stringWithFormat:@"已经在一起了%ld天",(long)a];
                //大于一天
            }else{
                //小于一天
                self.togetherLabel.text = @"已经在一起1天";
            }
                if (count>60*24) {
                    NSInteger a = count/1440;
                    self.countDownLabel.text = [NSString stringWithFormat:@"%ld天",(long)a];
                    //大于一天
                }else{
                    //小于一天
                    self.countDownLabel.text = @"1天";
                }
                
                
            
            
        }
    }];
    self.chiefViewTop = YES;
    [Utils animationMobileTimer:0.3 View:self.chiefView Rect:CGRectMake(0, 0, DeviceWidth, kChiefViewHeight)];
    
    
    
    
    self.userEnabled = YES;
    [self messageNumberChange];
}


- (void)messageNumberChange
{
    if (self.userEnabled&&self.sweetheart&&self.sweetheartUser) {
        EMConversation *conversation = [[EaseMob sharedInstance].chatManager conversationForChatter:self.sweetheartUser.objectId conversationType:eConversationTypeChat];
        
        NSInteger number = [conversation unreadMessagesCount];
        if (number>0) {
            self.unreadMessagesLabel.text = [NSString stringWithFormat:@"%ld",(long)number];
            self.redHotView.hidden = NO;
            self.messageImageView.image = [UIImage imageNamed:@"有消息"];
        }else{
            self.unreadMessagesLabel.text = @"";
            self.redHotView.hidden = YES;
            self.messageImageView.image = [UIImage imageNamed:@"空消息"];
        }
    }
}
- (void)clickMessage:(UIButton *)bt
{
    bt.enabled = NO;
    [bt setBackgroundImage:[UIImage imageWithColor:RGBA(233, 233, 233, 1)] forState:UIControlStateNormal];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        bt.enabled = YES;
        [bt setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    });
    
    
    if (self.userEnabled) {
        
        if ([self.delegate respondsToSelector:@selector(pushChatViewControllerUser:isPay:)]) {
            
            
            
            [self.delegate pushChatViewControllerUser:self.sweetheartUser isPay:NO];
        }
        
        
    }else{
        [self hint];
    }
}
- (void)clickTelephone:(UIButton *)bt
{
    bt.enabled = NO;
    [bt setBackgroundImage:[UIImage imageWithColor:RGBA(233, 233, 233, 1)] forState:UIControlStateNormal];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        bt.enabled = YES;
        [bt setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    });
    
    
    if (self.userEnabled) {
        
        bt.enabled = NO;
        [self.sweetheartUser refreshInBackgroundWithBlock:^(AVObject *object, NSError *error) {
             bt.enabled = YES;
            self.sweetheartUser = (MLUser *)object;
            [AVAnalytics event:[NSString stringWithFormat:@"首页_恋人"] label:@"打电话"]; //type是变量,表示用户类型
            if (!error) {
                NSString *str = @"其他";
                BOOL isSponsor = NO;
                
//                if ([Utils cheackConfigurationScreen]) {
//                    isSponsor = NO;
//                    str = @"其他";
//                }else{
//                    if (self.order&&[self.order.sponsor.objectId isEqualToString:[MLUser currentUser].objectId]) {
//                        //我是发起人
//                        if ([MLUser currentUser].balance<0.2) {
//                            [HUD Prompt:@"余额不足,电话额外消耗2时光/分钟"];
//                            return;
//                        }
//                        str = @"电话额外消耗2时光/分钟,是否继续";
//                        isSponsor = YES;
//                    }else if(self.isPayRelation&&self.order&&[self.order.winner.objectId isEqualToString:[MLUser currentUser].objectId]){
//                        str = @"主动给对方打电话免费哦";
//                        isSponsor = NO;
//                    }else{
//                        isSponsor = NO;
//                        str = @"其他";
//                    }
//                }
                
               
                if([str isEqualToString:@"其他"]){
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"callOutWithChatter" object:@{@"chatter":self.sweetheartUser.objectId, @"chatUser":self.sweetheartUser, @"type":[NSNumber numberWithInt:eCallSessionTypeAudio],@"isSponsor":[NSNumber numberWithBool:isSponsor]}];
                }else{
                    HUD*hud = [[HUD alloc]init];
                    [hud HUDImage:nil Title:@"提示" Content:[NSString stringWithFormat:@"%@",str,nil] CANCEL:@"取消" Confirm:@"确定"];
                    // __weak ChatViewController *weakSelf = self;
                    hud.Confirm  = ^{
                        
                        
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"callOutWithChatter" object:@{@"chatter":self.sweetheartUser.objectId, @"chatUser":self.sweetheartUser, @"type":[NSNumber numberWithInt:eCallSessionTypeAudio],@"isSponsor":[NSNumber numberWithBool:isSponsor]}];
                        //[ShareData shareData].callVC = weakSelf;
                    };
                    hud.Cancel = ^{
                        NSLog(@"取消");
                    };
                    [self addSubview:hud];
                }
            }else{
                [HUD Prompt:@"操作错误，请重新尝试"];
            }
        }];
        
        
    }else{
        [self hint];
    }
}
- (void)clickKiss:(UIButton *)bt
{
    bt.enabled = NO;
    [bt setBackgroundImage:[UIImage imageWithColor:RGBA(233, 233, 233, 1)] forState:UIControlStateNormal];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        bt.enabled = YES;
        [bt setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    });
    if (self.userEnabled) {
        if (self.kiss) {
            
            [HUD Prompt:@"您操作太快请稍候再试"];
            return;
        }
        self.kiss = YES;
        NSDictionary *ext = @{LITTLE_ACTION_TYPE_MOMODA: LITTLE_ACTION_TYPE_MOMODA_VALUE ,@"nickname":[MLUser currentUser].nickname};
        EMChatText *chatText = [[EMChatText alloc] initWithText:@"么么哒"];
        EMTextMessageBody *textBody = [[EMTextMessageBody alloc] initWithChatObject:chatText];
        EMMessage *message = [[EMMessage alloc] initWithReceiver:self.sweetheartUser.objectId bodies:@[textBody]];
        //message.isRead = YES;
        message.ext = ext;
        
        message.isReadAcked = YES;
        message.isDeliveredAcked = YES;
        message.deliveryState = eMessageDeliveryState_Delivered;
        [[EaseMob sharedInstance].chatManager insertMessageToDB:message append2Chat:YES];
        [[EaseMob sharedInstance].chatManager importDataToNewDatabase];
        [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.kiss = NO;
        });
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        static SystemSoundID soundIDKiss = 0;
        
        NSString * path = [[NSBundle mainBundle] pathForResource:@"recordStop" ofType:@"wav"];
        if (path) {
            AudioServicesCreateSystemSoundID( (__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundIDKiss );
        }
        AudioServicesPlaySystemSound( soundIDKiss );
    }else{
        [self hint];
    }
}
- (void)clickPoke:(UIButton *)bt
{
    
    bt.enabled = NO;
    [bt setBackgroundImage:[UIImage imageWithColor:RGBA(233, 233, 233, 1)] forState:UIControlStateNormal];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        bt.enabled = YES;
        [bt setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    });
    
    if (self.userEnabled) {
        if (self.poke) {
            
            [HUD Prompt:@"您操作太快请稍候再试"];
            return;
        }
        self.poke = YES;
        
        NSDictionary *ext = @{LITTLE_ACTION_TYPE_CHUO: LITTLE_ACTION_TYPE_CHUO_VALUE,@"nickname":[MLUser currentUser].nickname};
        
        EMChatText *chatText = [[EMChatText alloc] initWithText:@"戳一下"];
        EMTextMessageBody *textBody = [[EMTextMessageBody alloc] initWithChatObject:chatText];
        EMMessage *message = [[EMMessage alloc] initWithReceiver:self.sweetheartUser.objectId bodies:@[textBody]];
        //message.isRead = YES;
        message.ext = ext;
        
        message.isReadAcked = YES;
        message.isDeliveredAcked = YES;
        message.deliveryState = eMessageDeliveryState_Delivered;
        [[EaseMob sharedInstance].chatManager insertMessageToDB:message append2Chat:YES];
        [[EaseMob sharedInstance].chatManager importDataToNewDatabase];
        [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.poke = NO;
        });
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        static SystemSoundID soundIDPoke = 0;
       
        NSString * path = [[NSBundle mainBundle] pathForResource:@"recordStop" ofType:@"wav"];
        if (path) {
            AudioServicesCreateSystemSoundID( (__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundIDPoke );
        }
        AudioServicesPlaySystemSound( soundIDPoke );
    }else{
        [self hint];
    }
}
- (void)clickTime:(UIButton *)bt
{
    
    bt.enabled = NO;
    [bt setBackgroundImage:[UIImage imageWithColor:RGBA(233, 233, 233, 1)] forState:UIControlStateNormal];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        bt.enabled = YES;
        [bt setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    });
    
    if (self.userEnabled) {
        [Utils Hidden:self.timeView Bool:YES];
        
        
    }else{
        [self hint];
    }
}
- (void)clickMyHeadBt
{
    if (self.userEnabled) {
        if ([self.delegate respondsToSelector:@selector(pushUserDataViewControllerUser:)]) {
            [self.delegate pushUserDataViewControllerUser:[MLUser currentUser]];
        }
    }else{
        [self hint];
    }
}

- (void)clickTaHeadBt
{
    if (self.userEnabled) {
        if ([self.delegate respondsToSelector:@selector(pushUserDataViewControllerUser:)]){
            
            [self.delegate pushUserDataViewControllerUser:self.sweetheartUser];
            
            
        }
    }else{
        [self hint];
    }
}
//计算剩余时间
- (NSInteger)manageDateBeginDate:(NSDate *)beginDate presentDate:(NSTimeInterval)presentInterval
{
    NSTimeInterval begin = [beginDate timeIntervalSince1970];
    NSTimeInterval cha = (presentInterval - begin);
    return cha;
}
/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
